package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();//通信通道
        //1.定义独占的随机队列 2.定义交换机 3.用绑定键绑定
        //由服务器自动随机命名->不告诉服务器名字时,参数会有默认值:非持久 独占 自动删除
        String queue = c.queueDeclare().getQueue();//得到队列名
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);
        System.out.println("请输入绑定键,用空格隔开:");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");
        for (String key : a) {
            c.queueBind(queue, "topic_logs", key);
        }
        //从随机对列queue接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();//只为了测试打印出来看看,平时不用这个键
                System.out.println(key+" : "+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        c.basicConsume(queue, true, deliverCallback, cancelCallback);
    }
}
